<!--
 * @Author: doing
 * @Date: 2023-08-10 10:20:54
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-09-02 17:56:00
 * @FilePath: \background-management-system\src\pages\menu\index.vue
 * @Description: 
 * 菜单管理页面
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
-->

<template>
    <div>
        <el-card shadow="never" class="border-0" v-loading="loading">
            <list-header @create="handleCreate" @refresh="getData" />
            <el-tree :data="tableData" :props="{ label: 'name', children: 'children' }" node-key="id"
                :default-expanded-keys="defaultExpandedKeys">
                <template #default="{ node, data }">
                    <div class="custom-tree-node">
                        <el-tag size="small" :type="type(data)">{{ typeText(data) }}</el-tag>
                        <el-icon v-if="data.icon" :size="16" class="ml-2">
                            <component :is="data.icon" />
                        </el-icon>
                        <span>{{ data.name }}</span>

                        <div class="ml-auto">
                            <!-- <el-switch :modelValue="data.isDisabled" :active-value=true :inactive-value=false
                                @change="handleStatusChange($event, data)" class="mr-3" /> -->
                            <el-button link type="text" size="small" @click.stop="handleEdit(data)" v-permission="['menu:edit']">修改</el-button>
                            <el-button link type="text" size="small" @click.stop="handleCreate(data)" v-permission="['menu:add']">增加</el-button>

                            <el-popconfirm title="是否要删除该记录？" confirmButtonText="确认" cancelButtonText="取消"
                                @confirm="handleDelete(data.id)">
                                <template #reference>
                                    <el-button link type="text" size="small" v-permission="['menu:delete']">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </div>
                </template>
            </el-tree>
        </el-card>
        <!-- 添加新数据开始 -->
        <form-drawer ref="addMenuRef" :title="addMenuTitle" destroyOnClose @submit="addMenuSubmit" @clean="cleanAddForm">
            <el-form ref="addMenuFormRef" :model="addMenuForm" :rules="addMenuFormRules">
                <el-form-item label="类型：" prop="type" :label-width="formLabelWidth">
                    <el-radio-group v-model="addMenuForm.type" @change="AddchangeRadio">
                        <el-radio :label="1" border>目录</el-radio>
                        <el-radio :label="2" border>菜单</el-radio>
                        <el-radio :label="3" border>按钮</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="名称：" prop="name" :label-width="formLabelWidth">
                    <el-input v-model="addMenuForm.name"></el-input>
                </el-form-item>
                <!-- <el-form-item label="父节点：" prop="parentId" :label-width="formLabelWidth">
                    <el-input v-model="addMenuForm.parentId"></el-input>
                </el-form-item> -->
                <el-form-item label="权限标识：" prop="code" :label-width="formLabelWidth">
                    <el-input v-model="addMenuForm.code"></el-input>
                </el-form-item>
                <el-form-item label="请求地址：" prop="url" v-if="addMenuForm.type != 3" :label-width="formLabelWidth">
                    <el-input v-model="addMenuForm.url"></el-input>
                </el-form-item>
                <el-form-item label="图标：" prop="icon" v-if="addMenuForm.type != 3" :label-width="formLabelWidth">
                    <el-input v-model="addMenuForm.icon"></el-input>
                </el-form-item>
                <el-form-item label="排序：" prop="sort" :label-width="formLabelWidth">
                    <el-input-number v-model="addMenuForm.sort" :min="1" :max="10000" style="width: 300px">
                    </el-input-number>
                </el-form-item>
            </el-form>
        </form-drawer>

        <!-- 修改权限信息开始 -->
        <form-drawer  ref="updataMenuRef" :title="updataMenuTitle" destroyOnClose @submit="updataMenuSubmit" @clean="cleanEditForm">
            <el-form ref="updataMenuFormRef" :model="updataMenuForm" :rules="updataMenuFormRules">
                <el-form-item label="类型：" prop="type" :label-width="formLabelWidth">
                    <el-radio-group v-model="updataMenuForm.type" @change="EditchangeRadio">
                        <el-radio :label="1" border>目录</el-radio>
                        <el-radio :label="2" border>菜单</el-radio>
                        <el-radio :label="3" border>按钮</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="名称：" prop="name" :label-width="formLabelWidth">
                    <el-input v-model="updataMenuForm.name"></el-input>
                </el-form-item>
                <el-form-item label="权限标识：" prop="code" :label-width="formLabelWidth">
                    <el-input v-model="updataMenuForm.code"></el-input>
                </el-form-item>
                <el-form-item label="请求地址：" prop="url" v-if="updataMenuForm.type != 3" :label-width="formLabelWidth">
                    <el-input v-model="updataMenuForm.url"></el-input>
                </el-form-item>
                <el-form-item label="图标：" prop="icon" v-if="updataMenuForm.type != 3" :label-width="formLabelWidth">
                    <el-input v-model="updataMenuForm.icon"></el-input>
                </el-form-item>
                <el-form-item label="排序：" prop="sort" :label-width="formLabelWidth">
                    <el-input-number v-model="updataMenuForm.sort" :min="1" :max="10000" style="width: 300px">
                    </el-input-number>
                </el-form-item>
            </el-form>
        </form-drawer>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import ListHeader from '~/components/ListHeader.vue'
import FormDrawer from '~/components/FormDrawer.vue'
import { useStore } from 'vuex'
import {
    iconValidator
} from '~/composables/rule.js'
import {
    getMenus,
    updataMenu,
    addMenu,
    deleteMenu
} from '~/api/menu.js'
import {
    toast,
    showModal
} from '~/composables/util.js'

//初始化数据开始
const store = useStore()
const tableData = ref([])
const loading = ref(false)
//先做一些假数据
const defaultExpandedKeys = ref([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
const typeText = computed(()=>{
    return function(res){
        if(res.type === 1){
            return '目录'
        }else if(res.type === 2){
            return '菜单'
        }else{
            return '按钮'
        }
    }
})
const type = computed(()=>{
    return function(res){
        if(res.type === 1){
            return 'success'
        }else if(res.type === 2){
            return 'warning'
        }else{
            return 'info'
        }
    }
})

onMounted(() => {
    getData()
})

const getData = async function () {
    //加载的时候进行锁定滚动条
    // document.body.style.overflow = 'hidden'
    loading.value = true
    const body = {
        name : ''
    }
    
    await getMenus(body).then(res => {
        console.log(res)
        // console.log(res.data.data)
        tableData.value = res.data.data.data
    }).catch(err=>{
        console.log(err)
    })
    loading.value = false
    // document.body.style.overflow = 'scroll'
}

//初始化数据结束


//创建一个新的菜单权限开始
const addMenuRef = ref(null)
const addMenuTitle = ref('新增')
const addMenuFormRef = ref(null)
const addMenuForm = reactive({})
const formLabelWidth = '100px'
// const isAddItem = ref(false)  //用于检验是否为添加单个数据还是新的数据
//表单验证规则
const addMenuFormRules = {
    name: [
        {
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
        },
    ],
    code: [
        {
            required: true,
            message: '权限标识不能为空',
            trigger: 'blur'
        },
    ],
    url: [
        {
            required: true,
            message: '请求地址不能为空',
            trigger: 'blur'
        },
    ],
    icon: [
        {
            required: true,
            validator: iconValidator,
            trigger: 'blur'
        },
    ],
    remark: [
        {
            required: true,
            message: '备注不能为空',
            trigger: 'blur'
        },
    ],
}
//新增按钮事件
const handleCreate = async function ({ id,type } = {}) {
    addMenuRef.value.hideLoading()
    addMenuRef.value.open()
    addMenuForm.parentId = 0
    if(id){
        console.log(`父亲权限的类型是${type},父亲权限的id是${id}`)
        await nextTick(()=>{
            // isAddItem.value = true
            addMenuForm.parentId = id
        })
    }
}
//单选框触发事件
const AddchangeRadio = function(){
    //如何是类型3的话直接清除掉部分对象中的属性
    if(addMenuForm.type === 3){
        delete addMenuForm.url
        delete addMenuForm.icon
        console.log(addMenuForm)
    }
}
//离开抽屉组件事件
const cleanAddForm = function () {
    addMenuFormRef.value.resetFields()
}
//提交按钮事件
const addMenuSubmit = function () {
    const data = {...addMenuForm}
    console.log('提交的数据为:')
    console.log(data)
    addMenuFormRef.value.validate(async(valid) => {
        addMenuRef.value.showLoading()
        if (!valid) {
            //防止有人没有通过验证规则就点击了按钮
            addMenuRef.value.hideLoading()
            return false
        } else {
            const fn = addMenu(data)
            await fn.then(res => {
                // console.log(res)
                addMenuRef.value.close()
                toast('添加成功')
                getData()
            })
            .finally(() => {
                // isAddItem.value = false
                addMenuRef.value.hideLoading()
            })
        }
    })
}
//创建一个新的菜单权限结束


//修改菜单权限信息开始
const updataMenuRef = ref(null)
const updataMenuTitle = ref('更新')
const updataMenuFormRef = ref(null)
const updataMenuForm = reactive({})
const updataMenuFormRules = {
    name: [
        {
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
        },
    ],
    code: [
        {
            required: true,
            message: '权限标识不能为空',
            trigger: 'blur'
        },
    ],
    url: [
        {
            required: true,
            message: '请求地址不能为空',
            trigger: 'blur'
        },
    ],
    icon: [
        {
            required: true,
            validator: iconValidator,
            trigger: 'blur'
        },
    ],
    remark: [
        {
            required: true,
            message: '备注不能为空',
            trigger: 'blur'
        },
    ],
}

const handleEdit = async function (data) {
    console.log(updataMenuForm)
    // console.log(data)
    updataMenuRef.value.hideLoading()
    updataMenuRef.value.open()
    await nextTick(()=>{
        updataMenuForm.id = data.id
        updataMenuForm.type = data.type
        updataMenuForm.name = data.name
        updataMenuForm.parentId = data.parentId
        updataMenuForm.code = data.code
        updataMenuForm.sort = data.sort
        if(data.type !== 3){
            updataMenuForm.icon = data.icon
            updataMenuForm.url = data.url
        }
    })
}
const EditchangeRadio = function(){
    //如何是类型3的话直接清除掉部分对象中的属性
    if(updataMenuForm.type === 3){
        delete updataMenuForm.url
        delete updataMenuForm.icon
        console.log(updataMenuForm)
    }
}
const cleanEditForm = function () {
    updataMenuFormRef.value.resetFields()
}
const updataMenuSubmit = function(){
    console.log('提交的数据为:')
    console.log(updataMenuForm)
    updataMenuFormRef.value.validate(async(valid) => {
        updataMenuRef.value.showLoading()
        if (!valid) {
            //防止有人没有通过验证规则就点击了按钮
            updataMenuRef.value.hideLoading()
            return false
        } else {
            await updataMenu(updataMenuForm).then(res => {
                // console.log(res)
                updataMenuRef.value.close()
                toast('更新成功')
                getData()
            }).finally(() => {
                updataMenuRef.value.hideLoading()
            })
        }
    })
}
//修改菜单权限信息结束



//添加子菜单权限信息
const addChild = function (id) {

}
//是否删除该数据
const handleDelete = function (id) {
    showModal('是否要删除该数据?').then(async () => {
        toast('正在删除中...', 'info', false, 3000)
        await deleteMenu(id).then(res => {
            toast('删除成功')
            getData()
        }).finally(() => {
        })
    })
}

//监听swaitch的变化
const handleStatusChange = function (event, data) {
    // console.log(event)
    // console.log(data)
}

</script>
<style scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
    padding-right: 8px;
}

.el-tree-node__content {
    padding: 20px 0;
}
</style>